package com.cuitrip.business.bill;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.bill.model.UserAccount;
import com.cuitrip.business.bill.model.UserAccounts;
import com.cuitrip.business.tripservice.model.SelectMenu;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.tripservice.ui.SelectMenuFragment;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.jumper.FragmentJumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rx.bus.RxBus;
import com.lab.utils.ImageHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sheena on 16/4/29.
 */
public class WithdrawPageFragment extends CustomUiFragment implements IProxyCallback {
    public static final String ACCOUNT_KEY = "account";
    public static final String BALANCE_KEY = "balance";
    public static final String ALL_ACCOUNTS_KEY = "accounts";
    public static final int ACCOUNT_BANK = 1;

    private static final int DECIMAL_DIGITS = 2;//设置可输入的小数位数

    @Bind(R.id.account)
    TextView mAccountLayout;
    @Bind(R.id.et_withdraw)
    EditText etWithdraw;
    @Bind(R.id.total_money)
    TextView mTotalMoney;
    @Bind(R.id.withdraw_all)
    TextView withdrawAll;
    @Bind(R.id.money_type)
    TextView moneyType;
    @Bind(R.id.btn_withdraw)
    TextView withdrawButton;
    @Bind(R.id.desc)
    TextView withdrawDesc;
    @Bind(R.id.hint)
    IconTextView hint;
    @Bind(R.id.icon)
    ImageView mIcon;

    @Bind(R.id.bank_name)
    TextView mBankName;
    private UserAccount account;
    private String balance;
    private UserAccounts userAccounts;
    private String userAccountId;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private String money;

    public static WithdrawPageFragment newInstance(UserAccounts accounts, UserAccount userAccount, String totalMoney) {
        WithdrawPageFragment withdrawPageFragment = new WithdrawPageFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ACCOUNT_KEY, userAccount);
        bundle.putSerializable(ALL_ACCOUNTS_KEY, accounts);
        bundle.putString(BALANCE_KEY, totalMoney);
        withdrawPageFragment.setArguments(bundle);
        return withdrawPageFragment;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.wallet_withdraw_money);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarRightAreaName = getString(R.string.query_icon);

        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_withdraw);
        if (getArguments() != null) {
            account = (UserAccount) getArguments().getSerializable(ACCOUNT_KEY);
            balance = getArguments().getString(BALANCE_KEY);
            userAccounts = (UserAccounts) getArguments().getSerializable(ALL_ACCOUNTS_KEY);
        }
        return view;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        if (account != null) {
            mAccountLayout.setText(account.getAccountNumber());
            userAccountId = String.valueOf(account.getUserAccountId());
            ImageHelper.displayCtImage(account.getAccountIcon(), mIcon, null);
            mBankName.setText(account.getAccountAbbr());
            int type = account.getType();
            if (type == ACCOUNT_BANK) {
                withdrawDesc.setText(R.string.wallet_withdraw_desc);
            } else {
                withdrawDesc.setText(R.string.account_paypal_withdraw_desc);
            }
        }

        if (balance != null) {
            mTotalMoney.setText(getString(R.string.transaction_attribute_balance) + " " + balance);
        }

        if (userAccounts != null && userAccounts.getList().size() != 0) {
            hint.setVisibility(View.VISIBLE);
        } else {
            hint.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        InputFilter[] filters={new CashInputFilter()};
        etWithdraw.setFilters(filters);
    }


    @Override
    public void initListener() {
        etWithdraw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    String content = s.toString();
                    double money = Double.parseDouble(content);
                    double total = Double.parseDouble(balance);
                    if (money <= 0) {
                        withdrawAll.setVisibility(View.VISIBLE);
                        withdrawButton.setEnabled(false);
                        mTotalMoney.setTextColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
                        mTotalMoney.setText(getString(R.string.transaction_attribute_balance) + " " + balance);
                        moneyType.setTextColor(ResourceUtil.getColor(R.color.ct_black));
                        etWithdraw.setTextColor(ResourceUtil.getColor(R.color.ct_black));
                    } else if (money > total) {
                        withdrawAll.setVisibility(View.GONE);
                        mTotalMoney.setTextColor(ResourceUtil.getColor(R.color.red));
                        mTotalMoney.setText(R.string.wallet_withdraw_exceed);
                        moneyType.setTextColor(ResourceUtil.getColor(R.color.red));
                        etWithdraw.setTextColor(ResourceUtil.getColor(R.color.red));
                        withdrawButton.setEnabled(false);
                    } else if (money >= 0 && money <= total) {
                        withdrawAll.setVisibility(View.VISIBLE);
                        withdrawButton.setEnabled(true);
                        mTotalMoney.setTextColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
                        mTotalMoney.setText(getString(R.string.transaction_attribute_balance) + " " + balance);
                        moneyType.setTextColor(ResourceUtil.getColor(R.color.ct_black));
                        etWithdraw.setTextColor(ResourceUtil.getColor(R.color.ct_black));
                    }

                }
            }
        });
    }

    @OnClick(R.id.fl_account_layout)
    public void changeAccount() {
        if (userAccounts != null && userAccounts.getList() != null && userAccounts.getList().size() != 1) {
            final ArrayList<UserAccount> list = userAccounts.getList();
            SelectMenuFragment selectMenuFragment = new SelectMenuFragment();
            List<SelectMenu> selectMenuList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                SelectMenu selectMenu = new SelectMenu();
                selectMenu.key = String.valueOf(i);
                selectMenu.value = list.get(i).getAccountAbbr() + " " + list.get(i).getAccountNumber();
                selectMenuList.add(selectMenu);
            }
            selectMenuFragment.setTitle(getString(R.string.wallet_account));
            selectMenuFragment.setSelectMenuList(selectMenuList);
            showDialogFragment(selectMenuFragment);
            selectMenuFragment.setResultListener(new SelectMenuFragment.OnDataSelectBackListener() {
                @Override
                public void onSelect(SelectMenu selectMenu) {
                    int i = Integer.parseInt(selectMenu.key);
                    account = list.get(i);
                    ImageHelper.displayCtImage(account.getAccountIcon(), mIcon, null);
                    mBankName.setText(account.getAccountAbbr());
                    mAccountLayout.setText(account.getAccountNumber());
                    userAccountId = String.valueOf(account.getUserAccountId());
                    int type = account.getType();
                    if (type == ACCOUNT_BANK) {
                        withdrawDesc.setText(R.string.wallet_withdraw_desc);
                    } else {
                        withdrawDesc.setText(R.string.account_paypal_withdraw_desc);
                    }
                }
            });
        }
    }

    @OnClick(R.id.withdraw_all)
    public void withdrawAll() {
        if (!TextUtils.isEmpty(balance)) {
            etWithdraw.setText(balance);

        }
    }

    @OnClick(R.id.btn_withdraw)
    public void withdraw() {
        InputMethodManager ma = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getActivity().getCurrentFocus() != null) {
            ma.hideSoftInputFromWindow(getActivity().getCurrentFocus().getApplicationWindowToken(), 0);
        }
        if (!TextUtils.isEmpty(etWithdraw.getText())) {
            money = etWithdraw.getText().toString();
            ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
            choiceDialog.setDialogMessage(getResources().getString(R.string.wallet_withdraw_confirm, money, mBankName.getText().toString(), mAccountLayout.getText().toString()));
            choiceDialog.setDialogMessageVisibility(true);
            choiceDialog.setDialogTitleVisibility(false);
            choiceDialog.setDialogCoupleStyleSetting(
                    getResources().getString(R.string.operation_yes),
                    getResources().getString(R.string.operation_no), new ChoiceDialog.DialogStyleCoupleCallback() {
                        @Override
                        public boolean onPositiveButtonClick() {
                            showLoading();
                            UserBusiness.getCash(mApiProxy, "", money, "USD", userAccountId);
                            return false;
                        }

                        @Override
                        public boolean onNegativeButtonClick() {
                            return false;
                        }
                    });
            showDialogFragment(choiceDialog);

        }
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()){
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.isResponseNormal()) {
            hideLoading();
            if (response.getApiName().equals(ApiManager.GET_CASH)) {
                RxBus.getDefault().send(new WithdrawEvent());
                FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container, SubmitSucFragment.newInstance(money,account), SubmitSucFragment.class.getName(), true);
            }
            return false;
        } else {
            hideLoading();
            String msg = response.msg;
            FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container, SubmitFailedFragment.newInstance(account, userAccounts, balance,msg), SubmitFailedFragment.class.getName(), true);
            return false;
        }
    }
}
